package com.books4sale.admin.service;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONTokener;
import org.json.JSONWriter;

import com.books4sale.admin.dto.Book;
import com.books4sale.admin.dto.tools.Helper;
import com.books4sale.admin.dto.tools.PMF;
import com.google.appengine.api.users.User;

public class AddNewBookServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public AddNewBookServlet() {
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Helper helper = Helper.get();
		String bookName = req.getParameter(Helper.BOOK_NAME);
		String bookCollage = req.getParameter(Helper.BOOK_COLLAGE);
		String bookSubject = req.getParameter(Helper.BOOK_SUBJECT);
		String bookPrice = req.getParameter(Helper.BOOK_PRICE);

		User currentUser = helper.getCurrentUser();
		Date currentDate = helper.getCurrentDate();

		System.out.println("--------------------------->");
		Book book = new Book(currentUser, currentDate, bookName, bookCollage,
				bookSubject, bookPrice);
		System.out.println("----------------------------------<");
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");

		book = helper.insertBook(book);
		System.out.println("..............................................");
		if (null != book) {
			PrintWriter writer = resp.getWriter();
			
			JSONWriter jSONWriter = new JSONWriter(writer);
			try {
				jSONWriter.object()
				.key("bookId").value(book.getId().getId()+"")
				.key("bookName").value(book.getBookName())
				.key("bookCollage").value(book.getBookCollage())
				.key("bookSubject").value(book.getBookSubject())
				.key("bookPrice").value(book.getBookPrice()).endObject();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}
}
